include(CheckCXXCompilerFlag)

if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
    set(OPTIONS /W4 /WX)
    check_cxx_compiler_flag(/permissive HAS_PERMISSIVE_FLAG)
    if(HAS_PERMISSIVE_FLAG)
        set(OPTIONS ${OPTIONS} /permissive-)
    endif()

    check_cxx_compiler_flag(/std:c++20 HAS_CPP20_FLAG)
    check_cxx_compiler_flag(/std:c++23 HAS_CPP23_FLAG)
    check_cxx_compiler_flag(/std:c++latest HAS_CPPLATEST_FLAG)
elseif(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
    set(CMAKE_VERBOSE_MAKEFILE ON)
    set(OPTIONS -Wall -Wextra -pedantic-errors -Werror)

    check_cxx_compiler_flag(-std=c++20 HAS_CPP20_FLAG)
    check_cxx_compiler_flag(-std=c++23 HAS_CPP23_FLAG)
endif()

function(make_test src target std)
    add_executable(${target} ${src})
    target_compile_options(${target} PRIVATE ${OPTIONS})
    target_include_directories(${target} PRIVATE 3rdparty/Catch2/include)
    target_link_libraries(${target} PRIVATE ${CMAKE_PROJECT_NAME})
    set_target_properties(${target} PROPERTIES CXX_EXTENSIONS OFF)
    if(std)
        if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
            target_compile_options(${target} PRIVATE /std:${std})
        else()
            target_compile_options(${target} PRIVATE -std=${std})
        endif()
    endif()
    add_test(NAME ${target} COMMAND ${target})
endfunction()

make_test(test.cpp test-cpp17 c++17)
make_test(test_flags.cpp test_flags-cpp17 c++17)
make_test(test_aliases.cpp test_aliases-cpp17 c++17)
make_test(test_containers.cpp test_containers-cpp17 c++17)
make_test(test_wchar_t.cpp test_wchar_t-cpp17 c++17)

if(MAGIC_ENUM_OPT_ENABLE_NONASCII)
    make_test(test_nonascii.cpp test_nonascii-cpp17 c++17)
endif()

if(HAS_CPP20_FLAG)
    make_test(test.cpp test-cpp20 c++20)
    make_test(test_flags.cpp test_flags-cpp20 c++20)
    make_test(test_aliases.cpp test_aliases-cpp20 c++20)
    make_test(test_containers.cpp test_containers-cpp20 c++20)
    make_test(test_wchar_t.cpp test_wchar_t-cpp20 c++20)
    if(MAGIC_ENUM_OPT_ENABLE_NONASCII)
        make_test(test_nonascii.cpp test_nonascii-cpp20 c++20)
    endif()
endif()

if(HAS_CPP23_FLAG)
    make_test(test.cpp test-cpp23 c++23)
    make_test(test_flags.cpp test_flags-cpp23 c++23)
    make_test(test_aliases.cpp test_aliases-cpp23 c++23)
    make_test(test_containers.cpp test_containers-cpp23 c++23)
    make_test(test_wchar_t.cpp test_wchar_t-cpp23 c++23)
    if(MAGIC_ENUM_OPT_ENABLE_NONASCII)
        make_test(test_nonascii.cpp test_nonascii-cpp23 c++23)
    endif()
endif()

if(HAS_CPPLATEST_FLAG)
    make_test(test.cpp test-cpplatest c++latest)
    make_test(test_flags.cpp test_flags-cpplatest c++latest)
    make_test(test_aliases.cpp test_aliases-cpplatest c++latest)
    make_test(test_containers.cpp test_containers-cpplatest c++latest)
    make_test(test_wchar_t.cpp test_wchar_t-cpplatest c++latest)
    if(MAGIC_ENUM_OPT_ENABLE_NONASCII)
        make_test(test_nonascii.cpp test_nonascii-cpplatest c++latest)
    endif()
endif()
